<!--
 * @FilePath: /web-vue/src/views/SysUser/registerForm.vue
 * @Description: 【系统用户】新增表单
-->
<template>

    <!-- 弹出层-表单 -->
    <el-form class="edialog">
    
      <!-- <article class="sheader">
        <header>
            <el-avatar icon="el-icon-user-solid" shape="circle"></el-avatar>
          <span class="login" >
            <em class="bold">已有账号？</em>
            <a href="/login">
              <el-button type="primary" size="small">登录</el-button>
            </a>
          </span>
        </header>
      </article> -->
      <el-steps :active="active" finish-status="success">
        <el-step title="步骤 1"></el-step>
        <el-step title="步骤 2"></el-step>
      </el-steps>
  
      <section>
        <el-form
          ref="addForm"
          :model="addForm"
          :rules="rules"
          label-width="100px"
          class="demo-ruleForm"
          autocomplete="off"
        >
          <div v-if="active==0">
            <el-form-item prop="textarea">
              <el-input
                :value="addForm.textarea"
                type="textarea"
                :rows="10"
                :readonly="true"
              >
              </el-input>
            </el-form-item>
            <el-form-item prop="agreed">
              <el-checkbox v-model="addForm.agreed">同意注册协议</el-checkbox>
            </el-form-item>
          </div>
          <div v-if="active==1">
      
        <el-form-item label="用户名：" prop="username" size="mini">
          <el-input
            v-model="addForm.username"
            placeholder="请输入用户名"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="密码：" prop="password" size="mini">
          <el-input
            type="password"
            v-model="addForm.password"
            placeholder="请输入密码"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="姓名：" prop="realName" size="mini">
          <el-input
            v-model="addForm.realName"
            placeholder="请输入姓名"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="性别：" prop="sex" size="mini">
          <el-radio-group v-model="addForm.sex">
            <el-radio label="1">男</el-radio>
            <el-radio label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号：" prop="phone" size="mini">
          <el-input
            v-model="addForm.phone"
            placeholder="请输入手机号"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="电子邮箱：" prop="email" size="mini">
          <el-input
            v-model="addForm.email"
            placeholder="请输入电子邮箱"
            clearable
          ></el-input>
          <!-- <el-button v-bind:disabled="dis" v-bind:class="{grey:isGrey,blue:!isGrey}" idsize="mini" round @click="sendMsg">发送验证码</el-button>
              <span class="status">{{ statusMsg }}</span> -->

        <el-button v-bind:class="{grey:isGrey,blue:!isGrey}" 
            v-bind:disabled="dis" type="primary" 
            @click="sendMsg">
            <span v-if="show">发送验证码</span>
            <span v-else>重新发送({{count}}s)</span>
        </el-button>

        </el-form-item>
        <el-form-item label="验证码" prop="code">
              <el-input v-model="addForm.code" maxlength="4" />
            </el-form-item>

           

        <el-form-item label="身份类型：" prop="roleIds" size="mini">
          <el-select
            v-model="addForm.roleIds"
            filterable
            clearable
            placeholder="请选择你注册的身份类型"
            style="width: 99%"
          >
            <el-option label="我是房东" :value="5"> </el-option>
            <el-option label="我是租客" :value="7"> </el-option>
          </el-select>
        </el-form-item>
  
          </div>
        </el-form>
      </section>
      <div class="footer">
        <el-button
          v-if="active>0"
          type="primary"
          icon="el-icon-arrow-left"
          @click="prev"
        >上一步</el-button>
        <el-button
          v-if="active<step-1"
          type="primary"
          icon="el-icon-arrow-right"
          @click="next"
        >下一步</el-button>
        <el-button
          v-if="active==step-1"
          type="primary"
          @click="handleSubmit"
        >同意以下协议并注册</el-button>
        <div class="error">{{ error }}</div>
      </div>
      

    </el-form>
 
</template>

<script>

const dateTimePickerOption = {
  shortcuts: [
    {
      text: "今天",
      onClick(picker) {
        picker.$emit("pick", new Date());
      },
    },
    {
      text: "昨天",
      onClick(picker) {
        const date = new Date();
        date.setTime(date.getTime() - 3600 * 1000 * 24);
        picker.$emit("pick", date);
      },
    },
    {
      text: "一周前",
      onClick(picker) {
        const date = new Date();
        date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
        picker.$emit("pick", date);
      },
    },
  ],
};
// 正则
// 手机号
const phoneReg = /^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9]))\d{8}$/;
// 邮箱号
const emailReg =
  /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/;

// 手机号校验器
const phoneValidator = (rule, value, callback) => {
  if (phoneReg.test(value)) {
    callback();
  } else {
    callback(new Error("请输入正确格式的手机号！"));
  }
};
// 邮箱校验器
const emailValidator = (rule, value, callback) => {
  if (emailReg.test(value)) {
    callback();
  } else {
    callback(new Error("请输入正确格式的邮箱格式！"));
  }
};


export default {
  data() {
      return {
        
        dis: false,
      show: true,
      isGrey: false, //按钮样式
      timer: null, //设置计时器,
      count: "",



        visible: false,
        step: 2,
        active: 0,
        statusMsg: '',
        error: '',
        sendCode:false,
        addForm: {
          textarea: '请仔细阅读以下协议:租房网严格',
          agreed: false,
        username: null,
        password: null,
        realName: null,
        sex: null,
        duty: null,
        phone: null,
        email: null,
        roleIds: null,
        deptId: null,
        code: '',
      },

        rules: {

          


          agreed: [{
            validator: (rule, value, callback) => {
              console.log('value:' + value)
              if (value !== true) {
                callback(new Error('请确认同意注册协议'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }],
          
          username: [
          {
            required: true,
            message: "用户名不能为空！",
            trigger: "blur",
          },
        ],
        realName: [
          {
            required: true,
            message: "姓名不能为空！",
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            message: "密码不能为空！",
            trigger: "blur",
          },
          
        ],

        roleIds: [
          {
            required: true,
            message: "用户角色不能为空！",
            trigger: "blur",
          },
        ],
        code: [
          {
            required: true,
            message: "验证码不能为空！",
            trigger: "blur",
          },
        ],

        phone: [{ validator: phoneValidator, trigger: "blur" }],
        email: [{ validator: emailValidator, trigger: "blur" }],

        }
   
      }
      
    },
    layout: 'blank',
    methods: {

      getCode() {
      let TIME_COUNT = 5;
      if (!this.timer) {
        this.count = TIME_COUNT;
        this.isGrey = true;
        this.show = false;
        this.dis = true;
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) { 
            this.count--;
          } else {
            this.dis = false;
            this.isGrey = false;
            this.show = true;
            clearInterval(this.timer);
            this.timer = null;
          }
        }, 1000);
      }
      },


      sendMsg: function() {
        const self = this
        let namePass
        let emailPass
        if (self.timerid) {
          return false
        }
        this.$refs['addForm'].validateField('name', (valid) => {
          namePass = valid
        })
        self.statusMsg = ''
        if (namePass) {
          return false
        }
        this.$refs['addForm'].validateField('email', (valid) => {
          emailPass = valid
        })
        // 模拟验证码发送
        if (!namePass && !emailPass) {

          let TIME_COUNT = 5;
          if (!this.timer) {

          /* --------------------------- */
          let vueIns = this;
          // 请求参数
          let param = Object.assign({}, this.addForm);
          // 发起请求
          this.$api
            .getSysCode(param)
            .then((res) => {
              loading.close();
              let { status, message, data } = res.data; // 响应数据
           
            })
            .catch(function (err) {
              loading.close();
              vueIns.visible = false;
              console.log(`【系统用户】新增接口发生错误：${err}`);
            });
            /* --------------------------- */






            this.count = TIME_COUNT;
            this.isGrey = true;
            this.show = false;
            this.dis = true;
            this.timer = setInterval(() => {
              if (this.count > 0 && this.count <= TIME_COUNT) { 
                this.count--;
              } else {
                this.dis = false;
                this.isGrey = false;
                this.show = true;
                clearInterval(this.timer);
                this.timer = null;
              }
            }, 1000);
          }
       }
      },

      next: function() {
        if (this.active === 0) {
          this.$refs['addForm'].validateField('agreed', (valid) => {
            if (valid === '') {
              this.active++
            }
          })
        }
      },
      prev: function() {
        if (--this.active < 0) this.active = 0
      },
  
 
    

   // 打开【系统用户】表单新增窗口
   openAddForm(isShow) {
      this.visible = isShow;
    },

    // 关闭【系统用户】表单新增窗口
    handleCancel() {
      this.visible = false;
      this.$refs["addForm"].resetFields();
    },

    // 提交
    handleSubmit() {
      this.$refs["addForm"].validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            target: document.querySelector(".add-dialog"),
            lock: true,
            text: "正在保存，请耐心等待！",
          });

          let vueIns = this;
          // 请求参数
          let param = Object.assign({}, this.addForm);
          param["roleIds"] = [this.addForm.roleIds];
          // 发起请求
          this.$api
            .addSysUser(param)
            .then((res) => {
              loading.close();
              let { status, message, data } = res.data; // 响应数据
              if (status == 200) {
                this.$emit("afterSubmit");
                this.handleCancel();
                // 提示信息
                this.$message({
                  type: "success",
                  message: `操作成功！已新增【系统用户】!${message}`,
                  duration: 1680,
                });
                setTimeout(()=>{
                     window.location.reload()
                  } , 500)
              } else if (status == 403) {
                this.$message({
                  message: `权限不足！${message}`,
                  type: "error",
                  center: true,
                  duration: 1680,
                });
                // this.$router.push("/login");
              } else {
                this.$alert(`操作失败！${message}`, "【系统用户】新增", {
                  type: "error",
                  confirmButtonText: "确定",
                  callback: (action) => {},
                });
              }
            })
            .catch(function (err) {
              loading.close();
              vueIns.visible = false;
              console.log(`【系统用户】新增接口发生错误：${err}`);
            });
        }
      });
    },

     
    }
  }
  </script>
  
  <style  rel="stylesheet/scss" lang="scss">

.el-dialog {
    position: relative;
    margin: 0 auto 50px;
    border-radius: 21px;
    box-shadow: 0 1px 3px rgb(0 0 0 / 30%);
    box-sizing: border-box;
    width: 50%;
    height: 79%;
}


    .footer{
      text-align: center;
    }

  </style>
  